/**
 * @author: 善良的YWJ
 * Created by shanliangdeYWJ on 2020/09/09
 * @file: 10.3编写转换函数.js
 * @description: "
 * 
 *  请输入文件描述内容
 * 
 *              " 
 * @link [Github](https://github.com/shanliangdeYWJ)
 */

// 通常，多个组件需要反映相同的变化数据，
// 这时我们建议将共享状态提升到最近的共同父组件中去。
// 让我们看看它是如何运作的。

function toCelsius(fahrenheit) {
  return (fahrenheit - 32) * 5 / 9;
}
function toFahrenheit(celsius) {
  return (celsius * 9 / 5) + 32;
}

/** 依据一个输入框的值计算出另一个输入框的值。 */
function tryConvert(temperature, convert) {
  const input = parseFloat(temperature);
  // temperature 的值无效时，函数返回空字符串
  if (Number.isNaN(input)) { return ''; }

  const output = convert(input);
  // 保留三位小数并四舍五入后的转换结果
  const rounded = Math.round(output * 1000) / 1000;
  return rounded.toString();
}

// 测温组件
function BoilingVerdict(props) {
  if (props.celsius >= 100) { return <p>The water would boil.</p>; }
  return <p>The water would not boil.</p>;
}

const scaleNames = { c: 'Celsius', f: 'Fahrenhit' };

/** 负责接收 转换方法 和一个标识*/
class TemperatureInput extends React.Component {
  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(e) {
    this.props.onTemperatureChange(e.target.value);
  }

  render() {
    const temperature = this.props.temperature;
    const scale = this.props.scale;
    return (
      <fieldset>
        <legend>Enter temperature in {scaleNames[scale]}</legend>
        <input value={temperature} onChange={this.handleChange} />
      </fieldset>
    );
  }
}


class Calculator extends React.Component {
  constructor(props) {
    super(props);
    this.state = { temperature: '', scale: 'c' };

    this.handleCelsiusChange = this.handleCelsiusChange.bind(this);
    this.handleFahrenheitChange = this.handleFahrenheitChange.bind(this);

  }

  handleCelsiusChange(temperature) {
    this.setState({ scale: 'c', temperature });
  }

  handleFahrenheitChange(temperature) {
    this.setState({ scale: 'f', temperature });
  }

  render() {
    const scale = this.state.scale;
    const temperature = this.state.temperature;

    const celsius = scale === 'f'
      ? tryConvert(temperature, toCelsius)
      : temperature;

    const fahrenheit = scale === 'c'
      ? tryConvert(temperature, toFahrenheit)
      : temperature;

    return (
      <div>
        <TemperatureInput
          scale="c"
          temperature={celsius}
          onTemperatureChange={this.handleCelsiusChange} />

        <TemperatureInput
          scale="f"
          temperature={fahrenheit}
          onTemperatureChange={this.handleFahrenheitChange} />

        <BoilingVerdict celsius={parseFloat(celsius)} />
      </div>
    );
  }
}



const root = document.getElementById('root');

ReactDOM.render(<Calculator />, root);
